﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace GameStateManagement
{
    public class Target : Microsoft.Xna.Framework.DrawableGameComponent
    {
        public Matrix worldTransformMatrix;
        protected float fScale;
        protected Vector3 vWorldPosition;
        protected Quaternion qRotation;
        protected bool hasChanged;


        protected Model actorModel;
        protected ContentManager contentManager;
        protected Matrix[] actorBones;
        protected Utils.Timer timers;

        Vector4 vLightDirection;
        protected Effect celEffect;
        Texture2D m_CelMap, m_ColorMap;
        SpriteBatch spriteBatch;


        public BoundingSphere ModelBounds;
        public BoundingSphere WorldBounds;

        public bool followCam;
        protected Game game;

        public Target(Game game)
            : base(game)
        {
            this.game = game;
            timers = new Utils.Timer();
            worldTransformMatrix = Matrix.Identity;
            vWorldPosition = new Vector3(0.0f, 0.0f, 0.0f);
            fScale = 0.3f;
            qRotation = Quaternion.Identity;
            hasChanged = true;
            vLightDirection = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
            followCam = true;
        }

        public void updateRotation()
        {

            float fRadius = this.Position.Length();

            float fyAngle = (float)Math.Acos(this.Position.Y / fRadius);
            float fzAngle = (float)Math.Asin(this.Position.X / Math.Sqrt(Math.Pow(this.Position.X, 2) + Math.Pow(this.Position.Z, 2)));
            if (this.Position.Z < 0)
            {
                fzAngle = (float)Math.PI - fzAngle;
            }

            Quaternion siderot = Quaternion.CreateFromAxisAngle(Vector3.UnitY, fzAngle);
            Quaternion uprot = Quaternion.CreateFromAxisAngle(-Vector3.UnitX, (float)(Math.PI / 2.0) - fyAngle);

            this.Rotation = siderot * uprot;

            updateWorldTransformMatrix();

        }

        public override void Initialize()
        {

            base.Initialize();

        }

        public float Scale
        {
            get { return fScale; }
            set
            {
                fScale = value;
                hasChanged = true;
            }
        }

        public Vector3 Position
        {
            get { return vWorldPosition; }
            set
            {
                vWorldPosition = value;
                hasChanged = true;
            }
        }

        public Quaternion Rotation
        {
            get { return qRotation; }
            set { qRotation = value; }
        }

        public void switchCam()
        {
            followCam = !followCam;
        }

        public void updateWorldTransformMatrix()
        {
            Matrix scaleMatrix = Matrix.CreateScale(fScale);
            Matrix rotationMatrix = Matrix.CreateFromQuaternion(qRotation);
            Matrix translationMatrix = Matrix.CreateTranslation(vWorldPosition);

            worldTransformMatrix = scaleMatrix;
            worldTransformMatrix *= rotationMatrix;
            worldTransformMatrix *= translationMatrix;

            WorldBounds.Center = vWorldPosition;
            WorldBounds.Radius = ModelBounds.Radius * fScale;
        }

        public override void Update(GameTime gameTime)
        {


            timers.Update(gameTime);
            base.Update(gameTime);
        }

        public float getRadius()
        {
            return WorldBounds.Radius * 11.8f;
        }

        protected override void LoadContent()
        {
            contentManager = new ContentManager(Game.Services, "Content");
            actorModel = contentManager.Load<Model>("bubble");
            actorBones = new Matrix[actorModel.Bones.Count];


            celEffect = contentManager.Load<Effect>("Shader");
            m_CelMap = contentManager.Load<Texture2D>("Toon");
            m_ColorMap = contentManager.Load<Texture2D>("bubblegum");
            spriteBatch = new SpriteBatch(GraphicsDevice);

            foreach (ModelMesh mesh in actorModel.Meshes)
            {
                ModelBounds = BoundingSphere.CreateMerged(ModelBounds,
                mesh.BoundingSphere);
            }
            base.LoadContent();

        }

        protected void changeEffectUsedByModel(Model m, Effect e)
        {
            foreach (ModelMesh mesh in m.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    part.Effect = e;
                }
            }
        }

        protected override void UnloadContent()
        {
            contentManager.Unload();
            base.UnloadContent();
        }

        public override void Draw(GameTime gameTime)
        {


            //game.GraphicsDevice.SetRenderTarget(0, ((GameStateManagementGame)game).renderTarget);
            //GraphicsDevice.RenderState.DepthBufferEnable = true;
            actorModel.CopyAbsoluteBoneTransformsTo(actorBones);
            celEffect.CurrentTechnique = celEffect.Techniques["ToonShader"];
            changeEffectUsedByModel(actorModel, celEffect);
          
            foreach (ModelMesh mesh in actorModel.Meshes)
            {
                foreach (Effect effect in mesh.Effects)
                {
                    
                    Matrix world =  actorBones[mesh.ParentBone.Index] * worldTransformMatrix;
                    Matrix inverse = Matrix.Invert(world);
                    
                    if (followCam)
                    {
                        effect.Parameters["matWorldViewProj"].SetValue(world * GameplayScreen.camera.View * GameplayScreen.camera.Projection);
                       // effect.Projection = GameplayScreen.camera.Projection;
                    }
                    else
                    {
                        effect.Parameters["matWorldViewProj"].SetValue(world * GameplayScreen.CameraMatrix * GameplayScreen.ProjectionMatrix);
                    }
                    /*
                    effect.EnableDefaultLighting();
                    effect.PreferPerPixelLighting = true;
                    effect.AmbientLightColor = GameplayScreen.ambientLightColor;
                    effect.DirectionalLight0.DiffuseColor = GameplayScreen.diffuseColor;
                    effect.DirectionalLight0.Direction = GameplayScreen.diffuseDirection;
                    effect.SpecularColor = GameplayScreen.specularColor;
                    effect.SpecularPower = GameplayScreen.specularPower;*/

                    effect.Parameters["matInverseWorld"].SetValue(inverse);
                    effect.Parameters["vLightDirection"].SetValue(vLightDirection);
                    effect.Parameters["ColorMap"].SetValue(m_ColorMap);
                    effect.Parameters["CelMap"].SetValue(m_CelMap);

                }
                
                mesh.Draw();

            }
             
            
            //game.GraphicsDevice.SetRenderTarget(0, null);
            //Texture2D SceneTexture = renderTarget.GetTexture();

            //spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            //{
            //    // Apply the post process shader
            //    outlineEffect.Begin();
            //    {
            //        outlineEffect.CurrentTechnique.Passes[0].Begin();
            //        {
            //            outlineEffect.Parameters["Thickness"].SetValue(2.0f);
            //            outlineEffect.Parameters["Threshold"].SetValue(0.3f);

            //            spriteBatch.Draw(SceneTexture, new Rectangle(0, 0, 1024, 768), Color.White);
            //            //outlineEffect.CurrentTechnique.Passes[0].End();
            //        }
            //        outlineEffect.CurrentTechnique.Passes[0].End();
            //    }
            //    outlineEffect.End();
            //}
            //spriteBatch.End();
           

            base.Draw(gameTime);
        }

        


    }
}
